﻿CREATE TRIGGER [dbo].[trd_Loan_Borrower]
ON [dbo].[t_Loan_Borrower]
FOR DELETE
AS

UPDATE L_B SET Pos = L_B.Pos-1
FROM t_Loan_Borrower L_B
INNER JOIN deleted d ON d.LoanID = L_B.LoanID 
WHERE d.Pos < L_B.Pos

IF NOT EXISTS(SELECT * FROM deleted AS d INNER JOIN t_Loan_Borrower AS L_B ON d.LoanID = L_B.LoanID)BEGIN
	DECLARE @LoanID int SELECT @LoanID = LoanID FROM deleted d INNER JOIN t_Loan L ON L.ID = d.LoanID
	IF @LoanID > 0 EXEC s_Borrower_Add @LoanID,0
END

INSERT INTO v_Borrower_DeleteIfEmpty SELECT BorrowerID FROM deleted

